package com.hotline.communication.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ValidateUtil {

    private static final int MAXIMUM_CAPACITY = 1 << 30;


    private static final String NO_PARAM_MESSAGE = "缺少参数%s";

    /**
     * 校验参数是否非空
     *
     * @param param 带校验参数
     */
    public static void validate(Object param) {
        try {


        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 验证参数
     * @param map
     */
    public static void verifyParam(Map<String, Object> map){
        StringBuffer sb = new StringBuffer();
        map.forEach((key, value) -> {
            if (value == null) {
                sb.append(key).append("|");
            } else if (value instanceof String) {
                String str = String.valueOf(value);
                if (StringUtils.isBlank(str)) {
                    sb.append(key).append("|");
                }
            } else if (value instanceof List) {
                List list = (List)value;
                if (CollectionUtils.isEmpty(list)) {
                    sb.append(key).append("|");
                }
            }else if(value instanceof String[]){
                String[] s = (String[]) value;
                if(s.length < 1){
                    sb.append(key).append("|");
                }
            }
        });

        if (sb.length() > 0) {
            throw new RuntimeException(String.format(NO_PARAM_MESSAGE, sb));
        }
    }

    /**
     * 取自hashmap方法tableSizeFor(int cap)
     */
    private static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
}
